package com.itheima.edu.info.manajer.service;

import com.itheima.edu.info.manajer.dao.BaseStudentDao;
import com.itheima.edu.info.manajer.dao.OtherStudentDao;
import com.itheima.edu.info.manajer.dao.StudentDao;
import com.itheima.edu.info.manajer.domain.Student;
import com.itheima.edu.info.manajer.factory.StudentDaoFactory;

public class StudentService {
    //    创建StudentDao(库管)
//    private OtherStudentDao studentDao = new OtherStudentDao();

    //通过学生工厂类,获取库管对象
    BaseStudentDao studentDao = StudentDaoFactory.getStudentDao();
    public boolean addStudent(Student stu) {
        //1创建StudentDao(库管)
        //StudentDao studentDao = new StudentDao();→合并到上面,免得调用两次,占内存

//2把学生对象传递给StudentDao 库管中的addStudent方法
//3把返回值boolean类型的结果,返还给StudentController
        return studentDao.addStudent(stu);
    }

    /* isExists方法:
        1:从StudentDao中获取储存学生对象的数组,调用内部findAllStudent方法.该方法返回学生数组
        2遍历数组获取每一个学生对象,判断学号是否存在
        3返回true或者false的结果*/
    public boolean isExists(String id) {

        Student[] stus = studentDao.findAllStudent();
        //假设id在数组中不存在
        boolean exists = false;
        //遍历数组,获取每一个学生对象,准备判断
        for (int i = 0; i < stus.length; i++) {
            Student student = stus[i];
            if (student != null && student.getId().equals(id)) {
                exists = true;
                break;
            }

        }
        return exists;
    }

    public Student[] findAllStudent() {
        //1调用库管对象的findAllStudent获取学生对象数组
        Student[] allStudent = studentDao.findAllStudent();
        //2判断数组中是否有学生信息(有:返回地址,没有:返回null)
        //数组中只要有一个不是null的元素,那就代表有学生信息
        boolean flag = false;
        for (int i = 0; i < allStudent.length; i++) {
            Student stu = allStudent[i];
            if (stu != null) {
                flag = true;
                break;
            }
        }
        if (flag) {
            //有信息
            return allStudent;
        } else {
            //没有信息
            return null;
        }
    }

    public void deleteStudentById(String delId) {
        studentDao.deleteStudentById(delId);
    }

    public void updateStudent(String updateId, Student newStu) {
        studentDao.updateStudent(updateId, newStu);
    }
}
